EN_CH=en2ch=function(en){var ch={0:'报警',1:'正常','peak':'超声', 'temperature':'温度', 'press':'压力', 'voltage':'电压'}[en];return ch?ch:en;};
Charts=function(selector, dict, cacheLen){
	if(!cacheLen) cacheLen = 10;
	var singCacheLen = 10;
	var cacheLenPos = 0;
	if(cacheLen.length) singCacheLen = cacheLen[0];
	else singCacheLen = cacheLen
	$(selector).html((function(dict){var list = []; for(var key in dict) list.push(key); return list;})(dict).map(function(key){return "<div class=charts_black ></div>\n"+"<div class=charts-div id=charts-"+key+"></div>\n";}).join("\n"));
	return function(dict){var list = []; for(key in dict) list.push(key); return list;}(dict).map(function(key){
		var myChart = new Object();
		myChart.chart = echarts.init(document.getElementById('charts-'+key));
		myChart.yData = Array.apply(null, Array(singCacheLen)).map(function() {return null;});
		myChart.xData = Array.apply(null, Array(singCacheLen)).map(function() {return ' ';});
		if(cacheLen.length && cacheLenPos<cacheLen.length-1){
			cacheLenPos = cacheLenPos+1; singCacheLen = cacheLen[cacheLenPos];}
		myChart.resetQueue = function(){
			queue=function(list,value){list.shift();list.push(value);return queue;};
			if(dict[key].x.length && dict[key].y.length)
				for (i=0; i < function(a,b){return a<b?a:b;}(dict[key].x.length, dict[key].y.length); i++)
					queue(this.xData,dict[key].x[i])(this.yData,dict[key].y[i]);			
			else
				queue(this.xData,dict[key].x)(this.yData,dict[key].y);
			return this;
		};
		myChart.setOption = function(){this.chart.setOption({		
			title:{text: dict[key].name, x:'center'},
			xAxis:{type:'category',	data:this.xData},
			tooltip:{trigger:'axis', formatter: function(params){return (params[0].value[1]?params[0].value[1]:null);}},
			legend:{orient:'vertical', left:'right', data:dict[key].name},
			yAxis: {type:'value',	axisLabel:{formatter:'{value} '+dict[key].unit}},
			series: [{type:'line', data:this.yData, lineStyle:{color:dict[key].color}}]
			});
			return this;
		};
		return myChart;	
	}, dict);
};

function setCookie(c_name,value,expiredays){
	var exdate=new Date()
	exdate.setDate(exdate.getDate()+expiredays)
	document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString())
}

function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

function getURLString(name){
     var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
     var value = window.location.search.substr(1).match(reg);
     if(value!=null)return  unescape(value[2]); return null;
}

var postDataObj = null;
function postData(url, request, sync) {
	if(!sync) sync = false;
    $.ajax({
        type: "POST",  url: url, data:request,
		async : !sync,
        beforeSend: function(xhr, settings) { if (!(/^(GET|HEAD|OPTIONS|TRACE)$/.test(settings.type)) && !this.crossDomain) xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));},
        success: function (data){ postDataObj = eval('(' + data + ')'); },
        error:function(e){console.log(e);postDataObj = null;}
    });
    return postDataObj;
}

function setChartsData(dict, id){
	var msg = dict[id]; var node = {};
	if(!msg){  console.log("setChartsData: ", id, dict);  return null;   }
	for (var key in msg){ if(key == 'datetime')continue;var sub = msg[key];
		var dateTime = !!msg.datetime ? msg.datetime : sub.datetime;
		node[key] = {id:id, unit:sub.unit, x:dateTime, y:sub.value, color:'red', name:en2ch(key), alarm:en2ch(sub.alarm)};
	}return node;
}
/*
dict ={'peak': 	{unit:'dB', x:'abc', y:0, color:'red',	name: en2ch('peak')},
 		'temperature': 	{unit:'°C', x:'123', y:4, color:'blue',	name: en2ch('temperature')},
 		'press': 		{unit:'N',  x:'xyz', y:8, color:'green',name: en2ch('press')},
 		'voltage': 		{unit:'V',  x:['123', 'abc', 'def', ' '], y:[4,5,6,7], color:'red',	name: en2ch('voltage')},
 	};
*/ 

var formatDate = function (date) {  
    var y = date.getFullYear();  
    var m = date.getMonth() + 1;  
    m = m < 10 ? '0' + m : m;  
    var d = date.getDate();  
    d = d < 10 ? ('0' + d) : d;  
    return y + '-' + m + '-' + d;  
};

var formatDateTime = function (date) {  
	var y = date.getFullYear();  
	var m = date.getMonth() + 1;  
	m = m < 10 ? ('0' + m) : m;  
	var d = date.getDate();  
	d = d < 10 ? ('0' + d) : d;  
	var h = date.getHours();  
	h=h < 10 ? ('0' + h) : h;  
	var minute = date.getMinutes();  
	minute = minute < 10 ? ('0' + minute) : minute;  
	var second=date.getSeconds();  
	second=second < 10 ? ('0' + second) : second;  
	return y + '-' + m + '-' + d+' '+h+':'+minute+':'+second;  
};  


function isNull( str ){
	if ( str == "" ) return true;
	var regu = "^[ ]+$";
	var re = new RegExp(regu);
	return re.test(str);
}
function isEmail( str ){
	var myReg = /^[-_A-Za-z0-9]+@([_A-Za-z0-9]+.)+[A-Za-z0-9]{2,3}$/;
	if(myReg.test(str)) return true;
	return false;
}
function isNumberOr_Letter( s ){//英文字母和数字和下划线组成
	var regu = "^[0-9a-zA-Z_]+$";
	var re = new RegExp(regu);
	if (re.test(s)) return true;
	else return false;
}
function isDate(s){
	var myReg = /^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/;  
	if(myReg.test(s.trim())) return true;
	return false;
}
function isNumber(s) {
	var regu = "^[0-9]+$";
	var re  = new RegExp(regu);
	if (re.test(s)) return true;
	else return false;
}

function checkQuote(str) { // 检查输入的字符是否具有特殊字符
    var items = new Array("~", "`", "!", "@", "#", "$", "%", "^", "&", "\"", "{", "}", "[", "]", "(", ")");
    items.push(":", ";", "'", "|", "\\", "<", ">", "?", "/", "<<", ">>", "||", "//");
    items.push("root", "admin", "administrators", "administrator", "管理员", "系统管理员");
    items.push("select", "delete", "update", "insert", "create", "drop", "alter", "trancate");
    // str = str.toLowerCase();
    for (var i = 0; i < items.length; i++) {
        if (str.indexOf(items[i]) >= 0) {
            return true;
        }
    }
    return false;
}

function setGloballTableColor() {
	 $(".public_table tr").each(function (idx, item) {
           if(idx > 0 && idx%2==0)
               $(this).css("background-color"," #BBECDF");
           else
               $(this).css("background-color","#FFFACD");
     });  
}

function getDictLength(dict){
	var length = 0;
	for (var key in dict)
		length ++;
	return length;
}